package top.jnaw.jee.platform.controller.basics.extend;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;
import top.jnaw.jee.platform.Consts;
import top.jnaw.jee.platform.Consts.Result;
import top.jnaw.jee.platform.model.Feedback;
import top.jnaw.jee.platform.model.Users;
import top.jnaw.jee.utils.ModelResult;
import top.jnaw.jee.utils.Shiros;
import top.jnaw.jee.utils.Strings;

public class FeedbackController extends Controller {

  /**
   * 新增
   **/
  public void add() {
    ModelResult result = new ModelResult(Result.kBadParam);
    JSONObject req = Strings.toJSONObject(this);
    final String title = Strings.getString(req, "title", "");
    String version = Strings.getString(req, "version", "");
    String content = Strings.getString(req, "content", "");
    JSONArray images = Strings.getJSONArray(req, "images", null);
    Users user = Users.getByUsername(Shiros.getUser());
    int uid = (user != null) ? user.getId() : Consts.DEFAULT_BAD_ID;
    if (uid > 0) {
      result = Feedback.add(uid, title, version, content, images);
    }

    renderJson(result.toJsonId());
  }

  public void del() {
    ModelResult result = new ModelResult(Result.kModelDeleteError);
    JSONObject req = Strings.toJSONObject(this);
    JSONArray ids = Strings.getJSONArray(req, "ids", null);
    if (null != ids && ids.size() > 0) {
      for (int i = 0; i < ids.size(); i++) {
        if (Feedback.delete(ids.getInteger(i))) {
          result.setResult(Result.kSuccess);
        }
      }
    }
    renderJson(result.toJson());
  }

  /**
   * 查询
   **/
  public void list() {
    JSONObject req = Strings.toJSONObject(this);

    final int page = Strings.getInt(req, "page", Consts.DEFAULT_PAGE);
    final int size = Strings.getInt(req, "size", Consts.DEFAULT_PAGE_SIZE);
    final JSONArray filter = Strings.getJSONArray(req, "filter", null);
    Users user = Users.getByUsername(Shiros.getUser());
    int uid = (user != null) ? user.getId() : Consts.DEFAULT_BAD_ID;
    renderJson(Strings
        .formatJsonDateTime(
            Strings.formatPage(Feedback.list(page, size, filter, uid))));
  }

  /**
   * 查询详情
   **/
  public void query() {
    ModelResult result = new ModelResult(Result.kBadParam);

    JSONObject req = Strings.toJSONObject(this);
    final int id = Strings.getInt(req, "id", Consts.DEFAULT_BAD_ID);
    if (id > 0) {
      result = Feedback.query(id);
    }

    renderJson(result.toJson());
  }

  /**
   * 增加反馈
   **/
  public void addReply() {
    ModelResult result = new ModelResult(Result.kModelSaveError);

    JSONObject req = Strings.toJSONObject(this);
    final int fid = Strings.getInt(req, "fid", Consts.DEFAULT_BAD_ID);
    final String content = Strings.getString(req, "content", "");
    if (Feedback.addReply(fid, content)) {
      result.setResult(Result.kSuccess);
    }

    renderJson(result.toJson());
  }

}
